$(function(){
	/******************************************初始化******************************************/
	const table=layui.table;
	let params={
		pageSize:10,
		currPage:0,
		userId:sessionStorage.getItem('UserId')
	}
	// 我的申请表格实例
	const applicationTable=table.render({
		elem: '#productTable'
		,height: '.layui-tab-item'
		,data:[]
		// ,page: true //开启分页
		,cols: [[ //表头
			{type:'numbers', title: '序号', width:60}
			,{field: 'orderId', title: '申请编号', width:120}
			,{field: 'productName', title: '产品名称',templet:'#columnNickName'}
			,{field: 'status', title: '当前状态',templet: function (d) {
				let statusText='暂无'
					switch (d.status) {
						case -5:
							statusText = "已退款";
							break;
						case -4:
							statusText = "退款申请中";
							break;
						case -3:
							statusText = "已取消";
							break
						case -2:
							statusText = "审核完成";
							break
						case -1:
							statusText = "待审核";
							break;
						case 0:
							statusText='待支付'
							break;
						case 1:
							statusText = "支付完成";
							break;
						default:
							break;
					}
					return `<span>${statusText}</span>`
				}}
			,{field: 'productPrice', title: '申购价格'}
			// ,{field: 'productNum', title: '数量',templet: function (d){
			// 	return 	`<span>${d.productNum?d.productNum:0}</span>`
			// 	}}
			// ,{field: 'billingType', title: '计费方式',templet: function (d){
			// 	let billingTypeText
			// 		switch (d.billingType) {
			// 		case 2:
			// 			billingTypeText='按记录数据'
			// 			break;
			// 		case 3:
			// 			billingTypeText='按字节'
			// 			break;
			// 		case 4:
			// 			billingTypeText='按时长'
			// 			break;
			// 		default:
			// 			billingTypeText='按次数'
			// 			break
			// 	}
			// 		return `<span>${billingTypeText}</span>`
			// 	}}
			,{field: 'createTime', title: '申购日期',templet: function (d) {
					return `<span>${d.createTime ? `${d.createTime}`.slice(0,10): '————'}</span>`
				}}
			,{title: '操作',width:250,templet: function (d) {
					let statusHtml='';
					switch (d.status) {
						case -5:
						case -4:
						case -3:
						case -2:
							statusHtml=`<a class="layui-btn layui-btn-xs  layui-btn-primary" style="font-size:12px" lay-event="detail">详情</a>`;
							break
						case -1:
							statusHtml=`
									<a class="layui-btn layui-btn-xs  layui-btn-primary" style="font-size:12px" lay-event="detail">详情</a>
									<a class="layui-btn layui-btn-xs text-white layui-btn-danger" style="font-size:12px" lay-event="quit">撤销</a>
								`;
							break;
						case 0:
							statusHtml=`
									<a class="layui-btn layui-btn-xs  layui-btn-primary" style="font-size:12px" lay-event="detail">详情</a>
									<a class="layui-btn layui-btn-xs text-white layui-btn-danger" style="font-size:12px" lay-event="quit">撤销</a>
									<a class="layui-btn layui-btn-xs text-white layui-btn-primary" style="font-size:12px" lay-event="pay">支付</a>
								`;
							break;
						case 1:
							statusHtml=`
									<a class="layui-btn layui-btn-xs  layui-btn-primary" style="font-size:12px" lay-event="detail">详情</a>
									<a class="layui-btn layui-btn-xs  layui-btn-primary" style="font-size:12px" lay-event="downtown">下载</a>
									<a class="layui-btn layui-btn-xs text-white layui-btn-danger " style="font-size:12px" lay-event="refund">申请退款</a>
									<a class="layui-btn layui-btn-xs text-white layui-btn-warning" style="font-size:12px" lay-event="appraise">评价</a>
								`;
							break;
						default:
							break;
					}
					return statusHtml
				}}
		]]
	})
	/******************************************事件处理部分******************************************/
	// //产品
	// function productFun() {
	// 	$.ajax({
    //    		timeout:30000,
	// 		type: 'GET',
	// 		url: window.Http + "/orderProduct/list",
	// 		headers: {
	// 			'Authorization': "Bearer " + sessionStorage.getItem('Token')
	// 		},
	// 		data: { pageNum, pageSize,userId:sessionStorage.getItem('UserId')},
	// 		success: function (res) {
	// 			if (res.code == 200) {
	// 				$("#productTable tbody").empty()
	// 				if (res.rows && res.rows.length > 0) {
	// 					let html = "";
	// 					let statushtml = "";
	// 					let state = "可用";
	// 					let billingType = "按次数";
	// 					let herfUrl = "";
	// 					res.rows.forEach(function (val, index) {
	// 						herfUrl = "./productDetail.html?productId=" + val.productId;
	// 						if (val.status == 0) {
	// 							state = "待支付";
	// 							statushtml=`<td>
	// 										<a href="`+ herfUrl + `" class="layui-btn layui-btn-xs text-white" style="font-size:12px">查看</a>
	// 										<a class="layui-btn layui-btn-xs layui-btn-danger text-white payOrder" style="font-size:12px">支付</a>
	// 										<a class="layui-btn layui-btn-xs layui-btn-warm text-white auditRevoke" style="font-size:12px">撤销</a>
	// 										</td>`;
	// 						}else if (val.status == 1) {
	// 							state = "支付完成";
	// 							statushtml=`<td><a href="`+ herfUrl + `" class="layui-btn layui-btn-xs text-white" style="font-size:12px">查看</a>
	// 											<a class="layui-btn layui-btn-xs layui-btn-warm text-white applayRefundBtn" style="font-size:12px">申请退款</a>
	// 											<a class="layui-btn layui-btn-xs layui-btn-warm text-white evaluateBtn" style="font-size:12px">评价</a></td>`;
	// 						}else if (val.status == -1) {
	// 							state = "待审核";
	// 							statushtml=`<td>
	// 										<a href="`+ herfUrl + `" class="layui-btn layui-btn-xs text-white" style="font-size:12px">查看</a>
	// 										<a  class="layui-btn layui-btn-xs layui-btn-warm text-white auditRevoke" style="font-size:12px">撤销</a>
	// 										</td>`;
	// 						}else if (val.status == -2) {
	// 							state = "审核完成";
	// 							statushtml=`<td><a href="`+ herfUrl + `" class="layui-btn layui-btn-xs text-white" style="font-size:12px">查看</a></td>`;
	// 						}else if (val.status == -3) {
	// 							state = "已取消";
	// 							statushtml=`<td><a href="`+ herfUrl + `" class="layui-btn layui-btn-xs text-white" style="font-size:12px">查看</a></td>`;
	// 						}else if (val.status == -4) {
	// 							state = "退款申请中";
	// 							statushtml=`<td><a href="`+ herfUrl + `" class="layui-btn layui-btn-xs text-white" style="font-size:12px">查看</a></td>`;
	// 						}else if (val.status == -5){
	// 							state = "已退款";
	// 							statushtml=`<td><a href="`+ herfUrl + `" class="layui-btn layui-btn-xs text-white" style="font-size:12px">查看</a></td>`;
	// 						}
	// 						if(val.billingType == 2){
	// 							billingType = "按记录数据"
	// 						}else if(val.billingType == 3){
	// 							billingType = "按字节"
	// 						}else if(val.billingType == 4){
	// 							billingType = "按时长"
	// 						}else{
	// 							billingType = "按次数"
	// 						}
	//
	//
	// 						html += `<tr dataId="`+val.id+`" dataPrice="${val.productPrice}" dataProductId="${val.productId}" orderId="${val.orderId}">
	// 								<th scope="row">`+ (index + 1) + `</th>
	// 								<td style="width:100px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">`+ val.orderId + `</td>
	// 								<td>`+ val.productName + `</td>
	// 								<td>`+ state + `</td>
	// 								<td>￥ ${val.productPrice||0}元</td>
	// 								<td>${val.productNum||"不限制"}</td>
	// 								<td>`+ billingType + `</td>
	// 								<td>`+ `${val.createTime ? `${val.createTime}`.slice(0,10): '————'}` + `</td>
	// 								`+statushtml+`
	// 							</tr>`
	// 					})
	// 					$("#productTable tbody").append(html);
	// 				}else{
	// 					let html = `<tr><td scope="row" colspan="9" style="text-align:center">暂无数据</td></tr>`
	// 					$("#productTable tbody").append(html);
	// 				}
	// 				dataCount = res.total || 0;
	// 				if(pageNum == 1){
	// 					//执行一个laypage实例
	// 					layui.laypage.render({
	// 						elem: 'productTablePage', //注意，这里的 test1 是 ID，不用加 # 号
	// 						count: dataCount, //数据总数，从服务端得到
	// 						limit: 10,
	// 						groups: 5,
	// 						jump: function (obj, first) {
	// 							if(!first){
	// 							  pageNum = obj.curr;
	// 							  productFun();
	// 							}
	// 						}
	// 					});
	// 				}
	// 			}
	// 		}
	// 	})
	// }
	// productFun();
	table.on('tool(productTable)',function (obj) {
		const data = obj.data;
		const id = data.id;
		if (obj.event==='detail'){//查看
			// window.location.href='./productDetail.html?productId='+id;
			layer.open({
				type: 2,
				title: "产品订单详情",
				area: ['700px', '350px'],
				content: [`./popupPage/productOrdersDetail.html?id=${id}`]
			});
		}else if (obj.event==='quit'){//撤销
			$.ajax({
				timeout:30000,
				url: window.Http + "/orderProduct/cancelOrder/"+id,
				type: 'POST',
				headers: {
					'Authorization': "Bearer " + sessionStorage.getItem('Token')
				},
				contentType: 'application/json',
				// data: JSON.stringify({id:id}),
				success: function (res) {
					if (res.code === 200) {
						layer.msg("撤销成功");
					}else{
						layer.msg("撤销失败");
					}
				}
			})
		}else if(obj.event==='pay'){//支付
			layer.confirm('进行相关支付操作！', {icon: 3, title:'提示'}, function(index){
				$.ajax({
					timeout:30000,
					url: window.Http + "/orderProduct/paySuccess",
					type: 'POST',
					headers: {
						'Authorization': "Bearer " + sessionStorage.getItem('Token')
					},
					contentType: 'application/json',
					data: JSON.stringify({id:id}),
					success: function (res) {
						if (res.code === 200) {
							layer.msg(res.msg);
							// productFun()
							layer.close(index);
						}else{
							layer.msg(res.msg||"操作异常");
						}
					}
				})

			});
		}else if(obj.event==='downtown'){//下载
			let index = layer.load(1);
			$.ajax({
				timeout:30000,
				url: window.Http + '/dataProduct/execute',
				type: 'POST',
				headers: {
					'Authorization': "Bearer " + sessionStorage.getItem('Token')
				},
				data:JSON.stringify({

					"productId": data.productId,
					"type": 0//执行
				}),
				contentType: 'application/json',
				success: function (res) {
					layer.close(index);
					if (res.code === 200&&res.data.RetCode===0) {
						if (res.data&&res.data.Payload&&res.data.Payload.Result&&res.data.Payload.Result.length>0){
							const {Message}=res.data.Payload.Result[0];
							const url=Message.slice(4)
							console.log('url', url)
							window.location.href = url
						}else {
							layer.msg('下载url获取失败')
						}

					} else {
						layer.msg(res.msg==='操作成功' ?'操作失败':res.msg)
					}
				},
				error:function (){
					layer.close(index);
					layer.msg('请求下载失败')
				}
			})
			// layer.msg('还在开发中')
		}else if (obj.event==='refund'){//申请退款
			layer.open({
				type: 1,
				content: '<input class="form-control reason" placeholder="请输入退款原因" style="width:200px;margin:auto;margin-top:50px;">',
				title: '退款原因',
				area: ['400px','200px'],
				btn: ['确定'],
				yes: function(index){
					let reason = $('.reason').val();
					$.ajax({
						timeout:30000,
						url: window.Http + "/refund/apply",
						type: 'POST',
						headers: {
							'Authorization': "Bearer " + sessionStorage.getItem('Token')
						},
						contentType: 'application/json',
						data: JSON.stringify({'applyAmount':data.productPrice,'orderId': id,'reason':reason}),
						success: function (res) {
							if (res.code === 200) {
								layer.msg("申请成功，等待审核！");
								setTimeout(function (){
									layer.close(index)
								},1000)
							}else{
								layer.msg(`${res.msg}`);
								setTimeout(function (){
									layer.close(index)
								},1000)
							}
						}
					})
				}
			})

		}else if (obj.event==='appraise'){//评价
			window.dataId = id
			window.dataProductId = data.productId
			window.orderId = data.orderId
			layer.open({
				type: 2,
				title: "进行评价",
				area: ['600px', '350px'],
				content: ['./popupPage/orderEvaluatePop.html']
			});
		}
	})
	$("#exportOrder").click(function (e) {
		window.location.href = window.Http + "/orderProduct/export?userId="+sessionStorage.getItem('UserId')+"&Authorization="+sessionStorage.getItem('Token');
	})

	/******************************************功能函数部分******************************************/
	// // 支付
	// $("#productTable").delegate('.payOrder', 'click', function (e) {
	// 	let dataId = $(this).parents("tr").attr("dataId");
	// 	let idList = [];
	// 	idList[0] = dataId;
	// 	layer.confirm('进行相关支付操作！', {icon: 3, title:'提示'}, function(index){
	// 	  $.ajax({
    //    		timeout:30000,
	// 	  	url: window.Http + "/orderProduct/paySuccess",
	// 	  	type: 'POST',
	// 	  	headers: {
	// 	  		'Authorization': "Bearer " + sessionStorage.getItem('Token')
	// 	  	},
	// 		contentType: 'application/json',
	// 	  	data: JSON.stringify({idList:idList}),
	// 	  	success: function (res) {
	// 	  		if (res.code == 200) {
	// 				layer.msg(res.msg);
	// 				// productFun()
	// 	  			layer.close(index);
	// 	  		}else{
	// 				layer.msg(res.msg||"操作异常");
	// 			}
	// 	  	}
	// 	  })
	//
	// 	});
	//
	// })
	//
	// //撤销
	// $("#productTable").delegate(".auditRevoke","click",function(){
	// 	let dataId = $(this).parents("tr").attr("dataId");
	// 	let idList = [];
	// 	idList[0] = dataId;
	// 	$.ajax({
    //    		timeout:30000,
	// 	    url: window.Http + "/orderProduct/cancelOrder",
	// 	    type: 'POST',
	// 	    headers: {
	// 	        'Authorization': "Bearer " + sessionStorage.getItem('Token')
	// 	    },
	// 		contentType: 'application/json',
	// 		data: JSON.stringify({idList:idList}),
	// 	    success: function (res) {
	// 	        if (res.code == 200) {
	// 				layer.msg("撤销成功");
	// 	           setTimeout(function(){
	// 				   productFun();
	// 			   },1000)
	// 	        }else{
	// 				layer.msg("撤销失败");
	// 			}
	// 	    }
	// 	})
	// });
	// //申请退款
	// $("#productTable").delegate(".applayRefundBtn","click",function(){
	// 	let dataId = $(this).parents("tr").attr("dataId");
	// 	let productPrice = $(this).parents("tr").attr("dataPrice")
	// 	layer.open({
	// 		type: 1,
	// 		content: '<input class="form-control reason" placeholder="请输入退款原因" style="width:200px;margin:auto;margin-top:50px;">',
	// 		title: '退款原因',
	// 		area: ['400px','200px'],
	// 		btn: ['确定'],
	// 		yes: function(index){
	// 			let reason = $('.reason').val();
	// 			$.ajax({
    //    				timeout:30000,
	// 				url: window.Http + "/refund/apply",
	// 				type: 'POST',
	// 				headers: {
	// 					'Authorization': "Bearer " + sessionStorage.getItem('Token')
	// 				},
	// 				contentType: 'application/json',
	// 				data: JSON.stringify({'applyAmount':productPrice,'orderId': dataId,'reason':reason}),
	// 				success: function (res) {
	// 					if (res.code == 200) {
	// 						layer.msg("申请成功，等待审核！");
	// 					   setTimeout(function(){
	// 						   productFun();
	// 						   layer.close(index)
	// 					   },1000)
	// 					}else{
	// 						layer.msg(`${res.msg}`);
	// 						layer.close(index)
	// 					}
	// 				}
	// 			})
	// 		}
	// 	})
	//
	//
	// });
	// //评价
	// $("#productTable").delegate('.evaluateBtn', 'click', function (e) {
	// 	let dataId = $(this).parents("tr").attr("dataId");
	// 	let dataProductId = $(this).parents("tr").attr("dataProductId")
	// 	let orderId =  $(this).parents("tr").attr("orderId")
	// 	window.dataId = dataId
	// 	window.dataProductId = dataProductId
	// 	window.orderId = orderId
	// 	layer.open({
	// 		type: 2,
	// 		title: "进行评价",
	// 		area: ['600px', '350px'],
	// 		content: ['./popupPage/orderEvaluatePop.html']
	// 	});
	//
	// })
	//导出

	/**
	 * @description:函数描述 请求我的申请分页数据
	 * @return {Promise} 请求的结果
	 * @param params {Object}查询参数
	 */
	function applicationTableReq(params) {
		return new Promise((function (resolve, reject) {
			$.ajax({
				timeout:30000,
				type: 'GET',
				url: window.Http + "/orderProduct/list",
				headers: {
					'Authorization': "Bearer " + sessionStorage.getItem('Token')
				},
				data:params,
				success: function (res) {
					if (res.code===200){
						resolve(res)
					}else {
						layer.msg(res.msg)
						reject(new Error("请求失败")); // 失败时将错误传递给调用者
					}
				}
			})
		}))
	}
	/**
	 * @description:函数描述 渲染表格和分页
	 * @param params {Object}查询参数
	 */
	function tableRender(params){
		applicationTableReq(params).then(res=>{
			applicationTable.reload({data:res.rows})
			layui.laypage.render({
				elem: 'productTablePage', //注意，这里的 test1 是 ID，不用加 # 号
				count: res.total, //数据总数，从服务端得到
				limit: 10,
				groups: 5,
				jump: function (obj, first) {
					if(!first){
						params.currPage=obj.curr
						applicationTableReq(params).then(res=>{
							applicationTable.reload({data:res.rows})
						});
					}
				}
			});
		})
	}
	tableRender(params)
})
